package com.cm.sys.framework.utils;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cm.sys.framework.execption.BusinessException;

/***
 * 
 * @author yuqiang
 * @date 2019/07/08
 */

public class JsonUtil {

    public static String getString(JSONObject args, String key) {
        return getObject(args, key, String.class);
    }

    public static String getString(JSONObject args, String key, String defaultValue) {
        return getObject(args, key, String.class, defaultValue);
    }

    public static int getInt(JSONObject args, String key) {

        return getObject(args, key, Integer.class);
    }

    public static int getInt(JSONObject args, String key, int defaultValue) {
        return getObject(args, key, Integer.class, defaultValue);
    }

    public static Long getLong(JSONObject args, String key) {
        return getObject(args, key, Long.class);

    }

    public static Long getLong(JSONObject args, String key, Long defaultValue) {
        return getObject(args, key, Long.class, defaultValue);

    }

    public static Long getDouble(JSONObject args, String key) {
        return getObject(args, key, Long.class);

    }

    public static double getDouble(JSONObject args, String key, double defaultValue) {
        return getObject(args, key, Double.class, defaultValue);
    }

    public static Date getDate(JSONObject args, String key) {
        return getObject(args, key, Date.class);
    }

    public static Date getDate(JSONObject args, String key, Date defaultValue) {
        return getObject(args, key, Date.class, defaultValue);
    }

    public static JSONArray getJSONArray(JSONObject args, String key) {
        return getObject(args, key, JSONArray.class);
    }

    public static JSONArray getJSONArray(JSONObject args, String key, JSONArray defaultValue) {
        return getObject(args, key, JSONArray.class, defaultValue);
    }

    private static <T> T getObject(JSONObject args, String key, Class classType) {
        if (!args.containsKey(key)) {
            throw new BusinessException("JSON不存在名称" + key + "的属性");
        }
        T value = (T)args.getObject(key, classType);
        if (value == null || "".equals(value)) {
            throw new BusinessException("名称为" + key + "值为空");
        }
        return value;
    }

    private static <T> T getObject(JSONObject args, String key, Class classType, T defaultValue) {
        /*
         * if (!args.containsKey(key)) { throw new BusinessException("JSON不存在名称"
         * + key + "的属性"); }
         */
        T value = (T)args.getObject(key, classType);
        if (value == null || "".equals(value)) {
            return defaultValue;
        }
        return value;
    }
}
